

package com.zdsx.service.impl;

import com.zdsx.common.service.impl.BaseServiceImpl;
import com.zdsx.dao.CaffeineRepository;
import com.zdsx.dao.TokenDao;
import com.zdsx.entity.TokenEntity;
import com.zdsx.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;


@Service
public class TokenServiceImpl extends BaseServiceImpl<TokenDao, TokenEntity> implements TokenService {
	/**
	 * 1小时
	 */
	public final static int EXPIRE = 3600 * 1000;

	@Resource
	private CaffeineRepository caffeineRepository;

	public final static String TOKEN_CACHE_NAME = "token:user:info";

	@Override
	public TokenEntity getByToken(String token) {
		return baseDao.getByToken(token);
	}



	@Override
	public TokenEntity createToken(Long userId) {
		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1);

		//用户token
		String token;

		String oldToken = null;

		//判断是否生成过token
		TokenEntity tokenEntity = baseDao.getByUserId(userId);
		if(tokenEntity == null){
			//生成一个token
			token = generateToken();

			tokenEntity = new TokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateDate(now);
			tokenEntity.setExpireDate(expireTime);

			//保存token
			this.insert(tokenEntity);
		}else{
			oldToken = tokenEntity.getToken();
			//判断token是否过期
//			if(tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()){
//				//token过期，重新生成token
//				token = generateToken();
//			}else {
//				token = tokenEntity.getToken();
//			}
			// 全部都重新生成token
			token = generateToken();
			tokenEntity.setToken(token);
			tokenEntity.setUpdateDate(now);
			tokenEntity.setExpireDate(expireTime);

			//更新token
			this.updateById(tokenEntity);
		}

		// 清除缓存
		if (StringUtils.isNotBlank(oldToken)) {
			caffeineRepository.del(TOKEN_CACHE_NAME, oldToken);
		}

		return tokenEntity;
	}

	@Override
	public void updateToken(TokenEntity tokenEntity) {
		baseDao.updateById(tokenEntity);
		caffeineRepository.del(TOKEN_CACHE_NAME, tokenEntity.getToken());
	}

	@Override
	public void expireToken(Long userId){
		Date now = new Date();

		TokenEntity tokenEntity = new TokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setUpdateDate(now);
		tokenEntity.setExpireDate(now);

		this.updateById(tokenEntity);
		caffeineRepository.del(TOKEN_CACHE_NAME, tokenEntity.getToken());
	}



	private String generateToken(){
		return UUID.randomUUID().toString().replace("-", "");
	}
}
